package com.base.cn.platform.os.config;

import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.msg.SendMessageUtil;
import com.base.cn.platform.os.common.msg.WXTmpEnum;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.entity.course.catalog.CourseLiveReminder;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogBiz;
import com.base.cn.platform.os.service.course.catalog.CourseLiveReminderBiz;
import com.base.cn.platform.os.service.manage.op.affiche.OpReceiveAfficheService;
import com.base.cn.platform.os.service.qa.question.QaQuestionBiz;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时任务
 *
 * @author s.li
 * @date 2019/04/17
 */
@Component
@Slf4j
public class ScheduledTask {
    @Autowired
    private CourseCatalogBiz courseCatalogBiz;
    @Autowired
    private CourseLiveReminderBiz courseLiveReminderBiz;
    @Autowired
    private OpReceiveAfficheService opReceiveAfficheService;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    private QaQuestionBiz questionBiz;
    private static final String REFUND_CACHE_KEY = "qa_refund_schedule_cache_key";


    @Scheduled(cron = "0 0/5 * * * ?") //每5分钟执行一次
    //@Scheduled(cron = "0/10 * * * * ?")
    public void liveReminder(){
        //查询可要提醒的直播目录节点(开始直播前30分钟)
        List<CourseLiveReminder> liveReminderList = courseCatalogBiz.findCourseLiveReminderList();
        if(ObjectUtils.isNotEmpty(liveReminderList)){
            Set<BigDecimal> userIdSet = new HashSet<>();
            liveReminderList.forEach(e->userIdSet.add(e.getUserId()));
            List<BigDecimal> userIdList = new ArrayList<>(userIdSet);
            Map<BigDecimal,List> dataListMap = new HashMap<>();
            Map<BigDecimal,List<CourseLiveReminder>> liveReminderListMap = liveReminderList.stream().collect(Collectors.groupingBy(e->e.getUserId()));
            userIdList.forEach(userId->{
                List<Map<String,String>> list = new ArrayList<>();
                //courseData liveTime
                List<CourseLiveReminder> courseLiveReminderList = liveReminderListMap.get(userId);
                courseLiveReminderList.forEach(e->{
                    Map<String,String> map = new HashMap<>();
                    String courseData =e.getPackageCourse() ==null?"":e.getPackageCourse().getCourseName()+"->";
                    courseData += e.getCourse().getCourseName()+"->"+ e.getCatalogName();
                    map.put("courseData",courseData);
                    map.put("liveTime", DateUtils.format(e.getLessonStartTime(),"yyyy年MM月dd日 HH:mm"));
                    list.add(map);
                });
                dataListMap.put(userId,list);
            });

            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("userIdList",userIdList);
            dataMap.put("dataListMap",dataListMap);
            dataMap.put("key",WXTmpEnum.LIVE);
            SendMessageUtil.sendMessage(opReceiveAfficheService,customCacheChannel,dataMap);
            //先添加记录（避免下次重复发送）
            courseLiveReminderBiz.addCourseLiveReminder(liveReminderList);
            log.info("----------------------------------定时运行发送直播提醒");
        }
    }

    @Scheduled(cron = "0/10 * * * * ?")
    public void qaRefund(){
        log.info("----------------------问答退费定时器任务，每10秒执行一次");
        //设置redis缓存,防止重复退费,如果缓存key不为空跳过方法执行
        Date refundScheduleValue = (Date) customCacheChannel.get(J2CacheRegion.ONE_MINUTE_REGION.getKey(), REFUND_CACHE_KEY).getValue();
        if (ObjectUtils.isEmpty(refundScheduleValue)){
            customCacheChannel.set(J2CacheRegion.ONE_MINUTE_REGION.getKey(),REFUND_CACHE_KEY,new Date());
            questionBiz.qaRefund();
        }
    }
}
